package com.ysxsoft.wdg.ui.activity.login;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.socks.library.KLog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.event.CommentEvent;
import com.ysxsoft.wdg.bean.response.BindPhoneResponse;
import com.ysxsoft.wdg.bean.response.DaiKaiResponse;
import com.ysxsoft.wdg.bean.response.StOrderStatusDetailResponse;
import com.ysxsoft.wdg.bean.response.WxCheckResponse;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.ui.activity.MainActivity;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.ViewUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.widget.TimeCount;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.Call;

import static com.ysxsoft.wdg.bean.event.CommentEvent.EventStatus.REGISTER_OK;

public class BindPhoneActivity extends BaseActivity {
    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_finish)
    ImageView titleFinish;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.title_iv_r)
    ImageView titleIvR;
    @BindView(R.id.title_tv_r)
    TextView titleTvR;
    @BindView(R.id.et_invite)
    EditText etInvite;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.btn_code)
    TextView btnCode;
    @BindView(R.id.btn_register)
    TextView btnRegister;

    public static void start(Context context, String openid, String nickname, String avatar) {
        Intent intent = new Intent(context, BindPhoneActivity.class);
        intent.putExtra("openid", openid);
        intent.putExtra("nickname", nickname);
        intent.putExtra("avatar", avatar);
        context.startActivity(intent);
    }

    public static void startForResult(Activity activity, String openid, String nickname, String avatar, int code) {
        Intent intent = new Intent(activity, BindPhoneActivity.class);
        intent.putExtra("openid", openid);
        intent.putExtra("nickname", nickname);
        intent.putExtra("avatar", avatar);
        activity.startActivityForResult(intent,code);
    }

    private TimeCount timeCount;
    private String code = "", mobile = "", invicode = "", province = "", city = "", county = "";
    private String openid, nickname, avatar;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bind_phone;
    }

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        titleContent.setText("绑定手机号");
        timeCount = new TimeCount(60000, 1000, btnCode);
        openid = getIntent().getStringExtra("openid");
        nickname = getIntent().getStringExtra("nickname");
        avatar = getIntent().getStringExtra("avatar");
        initLocation();
    }

    @Override
    protected void setListener() {

    }

    @OnClick({R.id.title_finish, R.id.btn_code, R.id.btn_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
               finish();
                break;
            case R.id.btn_code:
                mobile = etPhone.getText().toString().trim();
                if (TextUtils.isEmpty(mobile)) {
                    ToastUtils.showToast("请输入手机号");
                    return;
                }
                if (mobile.length() != 11) {
                    ToastUtils.showToast("手机号格式不正确！");
                    return;
                }
                postCode();
                break;
            case R.id.btn_register:
                mobile = etPhone.getText().toString().trim();
                invicode = etInvite.getText().toString().trim();
                code = etCode.getText().toString().trim();

                if (TextUtils.isEmpty(code) || TextUtils.isEmpty(mobile) || TextUtils.isEmpty(invicode)) {
                    ToastUtils.showToast("输入信息不能为空...");
                    return;
                }
                if (mobile.length() != 11) {
                    ToastUtils.showToast("手机号码格式不正确...");
                    return;
                }
                postRegister();
                break;
        }
    }

    private void postRegister() {
        OkHttpUtils.post()
                .url(UrlHost.BIND_PHONE)
                .addParams("openid", openid)
                .addParams("nickname", nickname)//昵称
                .addParams("avatar", avatar)//头像
                .addParams("mobile", mobile)//手机号
                .addParams("invicode", invicode)//邀请码
                .addParams("a_cid", JPushInterface.getRegistrationID(BindPhoneActivity.this))
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    BindPhoneResponse bind = JsonUtils.parseByGson(response, BindPhoneResponse.class);
                    if (bind != null) {
                        if (CallbackCode.SUCCESS.equals(""+bind.getCode())) {//请求成功
//                            Intent intent=new Intent();
//                            setResult(RESULT_OK,intent);
//                            finish();

                            login(openid);
                        } else {
                            ToastUtils.showToast(bind.getMs());
                        }
                    }
                } else {
                }
            }
        });
    }

    private void postCode() {
        timeCount.start();
        mApiHelper.getMsmCode(mobile, new Observer<BaseBean<String>>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseBean<String> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    code = baseBean.getData();
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        ViewUtils.closeKeyboard(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
        mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
    }

    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    province = amapLocation.getProvince();
                    city = amapLocation.getCity();
                    county = amapLocation.getDistrict();
                    KLog.e("省--" + province + ",市--" + city + ",区--" + county);
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    KLog.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);


        new RxPermissions(this)
                .request(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) {
                        //启动定位
                        mLocationClient.startLocation();
                    }
                });
    }

    private void login(String open_id) {
        OkHttpUtils.post()
                .url(UrlHost.WX_CHECK)
                .addParams("openid", open_id)
                .addParams("a_cid", JPushInterface.getRegistrationID(BindPhoneActivity.this))
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    WxCheckResponse bean = JsonUtils.parseByGson(response, WxCheckResponse.class);
                    if (bean == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(bean.getCode())) {
                        WxCheckResponse.DataBean response1=bean.getData();
                        if(response1!=null){
                            String c=response1.getCode();
                            int uid=response1.getUid();
                            SharePrefUtils.saveUserId(uid+"");
                            SharePrefUtils.saveUserCode(c);
                            MainActivity.start(BindPhoneActivity.this);
                            finish();
                        }
                    } else if (CallbackCode.ERROR.equals(bean.getCode())) {
                        ToastUtils.showToast(bean.getMs());
                    }
                } else {
                }
            }
        });
    }
}
